/* test_io_func_uthread_open():
	A test for uthread_open(). Checks the regular case + the error
	case.

	This test doesn't create additional threads.
	We do:

	1)
	* Trys to open a non-exsiting file for reading with invalid name (and fail).

	2)
	* succesfully creates a file for writing (in current dir), write to it, and
	  then read from it.
*/


#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <time.h>

#include <fcntl.h>

#include "test_general.h"
#include "user_threads.h"
#include "user_io.h"


bool test_io_func_uthread_open();


bool test_io_func_uthread_open()
{
	init_individual_test();

	int tmp;

	if (initilize_uthread_in_each_test) {
		tmp = uthread_init();
		TEST_ASSERT(tmp == UTHREAD_SUCCESS);
	} 


	tmp = uthread_open("/dsffds/dsfdsf/dsfdsdfdsf/NOT_EXISTING.txt",O_RDONLY);
	TEST_ASSERT(tmp == -1);


	// Just creating the file (with permissions):
	int fd;
	fd = open("/tmp/TMP_file_with_random_data.txt",O_WRONLY | O_CREAT, 0777);
	TEST_ASSERT(fd >= 0);
	tmp = close (fd);
	TEST_ASSERT(tmp == 0);


	fd = uthread_open("/tmp/TMP_file_with_random_data.txt",O_WRONLY);
	TEST_ASSERT(fd >= 0);

	srand(time(NULL));
	int r = rand() %1000;

	tmp = uthread_write(fd,&r, sizeof(r));
	TEST_ASSERT(tmp == sizeof(r));

	tmp = close(fd);
	TEST_ASSERT(tmp == 0);



	fd = uthread_open("/tmp/TMP_file_with_random_data.txt",O_RDONLY);
	TEST_ASSERT(fd >= 0);


	int read_val;
	tmp = uthread_read(fd,&read_val, sizeof(read_val));
	TEST_ASSERT(tmp == sizeof(read_val));
	TEST_ASSERT(read_val == r);

	tmp = close(fd);
	TEST_ASSERT(tmp == 0);

	return true;
}

